package com.daoliuhe.scaffold.service.impl;

import com.daoliuhe.scaffold.mapper.ListEntryMapper;
import com.daoliuhe.scaffold.mapper.ListNameMapper;
import com.daoliuhe.scaffold.model.ListEntry;
import com.daoliuhe.scaffold.service.ListEntryService;
import com.daoliuhe.scaffold.tools.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

@Service
public class ListEntryServiceImpl implements ListEntryService {

    private static final Logger logger = LoggerFactory.getLogger(ListEntryServiceImpl.class);

    @Autowired
    ListEntryMapper listEntryMapper;

    @Autowired
    ListNameMapper listNameMapper;

    /**
     * 根据父id查找一级子节点
     */
    @Override
    public Object getChildOneLevelData(ListEntry entry) {
        logger.info("getChildOneLevelData,entry:{}", entry);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", listEntryMapper.getOneLevelPageCount(entry));
        map.put("rows", listEntryMapper.getOneLevelPageData(entry));
        return map;
    }

    /**
     * 根据列表名称和列表项的值查询分页数据
     */
    @Override
    public Object getPageData(ListEntry entry) {
        logger.info("getPageData,entry:{}", entry);
        Map<String, Object> map = new HashMap<String, Object>();
        int pageCount;
        List<ListEntry> pageData;
        //只有传入的listType为1时，才去查层叠列表项
        if (!StringUtils.isEmpty(entry) && Constants.LIST_CASCADE.equals(entry.getListType())) {
            pageCount = listEntryMapper.getCascadePageCount(entry);
            pageData = listEntryMapper.getCascadePageData(entry);
        } else {
            pageCount = listEntryMapper.getPageCount(entry);
            pageData = listEntryMapper.getPageData(entry);
        }
        map.put("total", pageCount);
        map.put("rows", pageData);
        return map;
    }

    /**
     * 根据列表名称和列表项的值查询全部数据
     */
    @Override
    public Object getAllData(ListEntry entry) {
        logger.info("getAllData,entry:{}", entry);
        return listEntryMapper.getAllData(entry);
    }

    @Override
    public Object selectTreeData(ListEntry entry) {
        logger.info("selectTreeData,entry:{}", entry);
        return listEntryMapper.selectTreeData(entry);
    }

    @Override
    public Object saveBatchValues(String listId, String parentId, String entryValues, String listNameApi) {
        logger.info("saveBatchValues,listId:{},parentId:{},entryValues:{},listNameApi:{}"
                , listId, parentId, entryValues, listNameApi);
        Map<String, Object> json = new HashMap<String, Object>();
        boolean success = false;
        StringBuilder reason = new StringBuilder();
        if (StringUtils.isEmpty(listId) || StringUtils.isEmpty(entryValues)) {
            reason.append("参数错误或者不符合格式!");
        } else {
            List<String> errors = new ArrayList<String>();
            List<String> numErrors = new ArrayList<String>();
            List<String> exists = new ArrayList<String>();
            List<String> lines = new ArrayList<String>();
            List<ListEntry> list = new ArrayList<ListEntry>();

            // 替换中文的逗号和冒号
            entryValues = entryValues.replaceAll("，", ",");
            entryValues = entryValues.replaceAll("：", ":");
            // 格式: 值1：[描述]:[排序编号],值2：[描述]:[排序编号] 描述和排序编号可有可无
            for (String entry : entryValues.split(",")) {
                entry = entry.trim();
                if (!StringUtils.isEmpty(entry)) {
                    String[] arr = entry.split(":");
                    if (arr.length != 1 && arr.length != 3) {
                        errors.add(entry);
                    } else if (arr.length == 3 && !isNumOrEmpty(arr[2])) {
                        numErrors.add(entry);
                    } else {
                        ListEntry queryBean = new ListEntry();
                        queryBean.setListId(listId);
                        queryBean.setParentId(parentId);
                        queryBean.setEntryValue(arr[0].trim());

                        if (!listEntryMapper.selectByEntryValue(queryBean).isEmpty()) {
                            exists.add(entry);
                        } else {
                            ListEntry bean = new ListEntry();
                            bean.setListId(listId);
                            bean.setParentId(parentId);
                            bean.setEnabled("1");
                            bean.setEntryValue(arr[0].trim());

                            if (arr.length == 3) {
                                bean.setDescription(arr[1]);
                                bean.setSortNumber(arr[2]);
                            }
                            list.add(bean);
                        }
                    }
                }
            }
            if (errors.isEmpty() && numErrors.isEmpty() && lines.isEmpty() && !list.isEmpty()) {
                //批量保存
                for (ListEntry le : list) {
                    String leParentId = le.getParentId();
                    //没有父节点，设置当前的fullValue为列表值
                    if (StringUtils.hasText(leParentId) && !"0".equalsIgnoreCase(leParentId)) {
                        //有父节点，设置当前的fullValue为父亲的fullValue加自己的列表值
                        ListEntry parentEntry = listEntryMapper.selectByPrimaryKey(new BigDecimal(parentId));
                        if (null != parentEntry && StringUtils.hasText(parentEntry.getEntryFullValue())) {
                            le.setEntryFullValue(parentEntry.getEntryFullValue() + "_" + le.getEntryValue());
                        }
                    } else {
                        le.setEntryFullValue(le.getEntryValue());
                    }
                    listEntryMapper.insertSelective(le);
                }
                //listEntryMapper.saveBatchValues(list);
                success = true;
            } else {
                if (!errors.isEmpty()) {
                    reason.append(String.format(" 项 %s 不符合填写规范", Arrays.toString(errors.toArray())));
                }
                if (!numErrors.isEmpty()) {
                    reason.append(String.format(" 项 %s 排序编号必须为数字", Arrays.toString(numErrors.toArray())));
                }
				if (!exists.isEmpty()) {
					reason.append(String.format(" 项 %s 在列表中已存在", Arrays.toString(exists.toArray())));
				}
                if (!lines.isEmpty()) {
                    reason.append(String.format(" 项 %s 不能包含下划线", Arrays.toString(lines.toArray())));
                }
                if (list.isEmpty()) {
                    reason.append("没有有效的添加项");
                }
            }
        }
        json.put("success", success);
        json.put("reason", reason.toString());
        return json;
    }

    private boolean isNumOrEmpty(String str) {
        logger.info("isNumOrEmpty,str:{}", str);
        return StringUtils.isEmpty(str) || str.matches("^\\d*$");
    }

    @Override
    public Object saveOrUpdate(ListEntry entry) {
        logger.info("saveOrUpdate,entry:{}", entry);
        Map<String, Object> json = new HashMap<String, Object>();
        boolean success = true;
        StringBuilder reason = new StringBuilder();
        if (!isNumOrEmpty(entry.getSortNumber())) {
            reason.append("排序编号必须为数字!");
            success = false;
        } else if (StringUtils.isEmpty(entry.getId())) {
            if (listEntryMapper.selectByEntryValue(entry).isEmpty()) {
                listEntryMapper.insert(entry);
            } else {
                reason.append("列表值已经存在!");
                success = false;
            }
        } else {
            ListEntry queryBean = new ListEntry();
            queryBean.setId(entry.getId());
            queryBean.setListId(entry.getListId());
            queryBean.setParentId(entry.getParentId());
            queryBean.setEntryValue(entry.getEntryValue());
            List<ListEntry> otherEntry = listEntryMapper.selectOtherByEntryValue(queryBean);
            if(otherEntry.isEmpty()){
                listEntryMapper.updateByPrimaryKeySelective(entry);
            } else {
                reason.append("列表值已经存在!");
                success = false;
            }
        }
        json.put("success", success);
        json.put("reason", reason.toString());
        return json;
    }

    @Override
    public Object saveOrUpdateNode(ListEntry entry) {
        logger.info("saveOrUpdate,entry:{}", entry);
        Map<String, Object> json = new HashMap<String, Object>();
        boolean success = true;
        StringBuilder reason = new StringBuilder();
        if (!isNumOrEmpty(entry.getSortNumber())) {
            reason.append("排序编号必须为数字!");
            success = false;
        } else {
            String parentId = entry.getParentId();
            String entryValue = entry.getEntryValue();
            //没有父节点，设置当前的fullValue为列表值
            if (StringUtils.hasText(parentId) && !"0".equalsIgnoreCase(parentId)) {
                //有父节点，设置当前的fullValue为父亲的fullValue加自己的列表值
                ListEntry parentEntry = listEntryMapper.selectByPrimaryKey(new BigDecimal(parentId));
                if (null != parentEntry && StringUtils.hasText(parentEntry.getEntryFullValue())) {
                    entry.setEntryFullValue(parentEntry.getEntryFullValue() + "_" + entryValue);
                }
            } else {
                entry.setEntryFullValue(entryValue);
            }
            if (StringUtils.isEmpty(entry.getId())) {
                if (listEntryMapper.selectByEntryValue(entry).isEmpty()) {
                    //插入的时候，只考虑自己的fullValue
                    listEntryMapper.insertSelective(entry);
                } else {
                    reason.append("列表值已经存在!");
                    success = false;
                }

            } else {
                ListEntry queryBean = new ListEntry();
                queryBean.setId(entry.getId());
                queryBean.setListId(entry.getListId());
                queryBean.setParentId(entry.getParentId());
                queryBean.setEntryValue(entry.getEntryValue());
                List<ListEntry> otherEntry = listEntryMapper.selectOtherByEntryValue(queryBean);
                if(otherEntry.isEmpty()){
                    //更新的时候，除了更新自己的fullValue,还需要更新自己后代的fullValue
                    listEntryMapper.updateByPrimaryKeySelective(entry);
                    updateChildren(entry, 1);
                } else {
                    reason.append("列表值已经存在!");
                    success = false;
                }
            }
        }
        json.put("success", success);
        json.put("reason", reason.toString());
        return json;
    }

    /**
     * 父节点更新，更新子节点的fullValue
     * 层级不能超过20层
     * @param listEntry
     * @param level
     */
    private void updateChildren(ListEntry listEntry, int level) {
        logger.info("updateChildren,listEntry:{}, level:{} ", listEntry, level);
        level++;
        //控制层级不能超过20层
        if (level > 20) {
            return;
        }
        String id = listEntry.getId().toString();
        String fatherFullValue = listEntry.getEntryFullValue();
        List<ListEntry> children = listEntryMapper.selectChildren(listEntry.getListId(), id);
        if (children.isEmpty()) {
            return;
        } else {
            for (ListEntry entry : children) {
                //更新自己
                String entryValue = entry.getEntryValue();
                if (StringUtils.hasText(fatherFullValue) && StringUtils.hasText(entryValue)) {
                    String entryFullValue = fatherFullValue + "_" + entryValue;
                    entry.setEntryFullValue(entryFullValue);
                    listEntryMapper.updateByPrimaryKeySelective(entry);
                }
                //更新后代节点
                updateChildren(entry, level);
            }
        }
    }

    @Override
    public List<ListEntry> selectByEntryValue(ListEntry entry) {
        return listEntryMapper.selectByEntryValue(entry);
    }

    @Override
    public List<ListEntry> selectByListApiName(String name) {
        logger.info("selectByListApiName,name:{}", name);
        return listEntryMapper.selectByListApiName(name);
    }

    @Override
    public String selectFullName(int id) {
        logger.info("selectFullName,id:{}", id);
        StringBuilder ret = new StringBuilder();
        List<ListEntry> retList = listEntryMapper.selectParents(id);
        for (int i = 0; i < retList.size(); i++) {
            ListEntry entry = retList.get(i);
            ret.append(entry.getEntryValue());
            if (i != retList.size() - 1) {
                ret.append("_");
            }
        }
        return ret.toString();
    }

    @Override
    public void updateBatchDisable(ArrayList<String> ids) {
        logger.info("batchDisable,ids:{}", ids);
        listEntryMapper.updateBatchDisable(ids);
    }

    @Override
    public void updateBatchEnable(ArrayList<String> ids) {
        logger.info("batchEnable,ids:{}", ids);
        listEntryMapper.updateBatchEnable(ids);
    }

    @Override
    public Map<String, Object> checkSimpleEntryRepeat(String listId, String entryValues) {
        logger.info("checkSimpleEntryRepeat,listId:{},entryValues:{}", listId, entryValues);
        Map<String, Object> retMap = new HashMap<String, Object>();
        List<String> entryValueList = new ArrayList<String>();
        //超长错误
        List<String> longErrors = new ArrayList<String>();
        //输入重复
        List<String> inputRepeatErrors = new ArrayList<String>();
        //不是数字
        List<String> notNumberErrors = new ArrayList<String>();
        //格式不匹配
        List<String> matchErrors = new ArrayList<String>();
        //系统已经存在
        List<String> inputExistErrors = new ArrayList<String>();
        //循坏判断
        if (StringUtils.hasText(entryValues)) {
            //替换中文的分号和冒号
            entryValues = entryValues.replaceAll("；", ";");
            entryValues = entryValues.replaceAll("：", ":");
            String[] values = entryValues.split(";");
            for (String value : values) {
                if (StringUtils.hasText(value)) {
                    String[] vals = value.split("::");
                    if (vals.length == 1) {
                        String val = vals[0];
                        //输入重复
                        if (StringUtils.hasText(val) && entryValueList.contains(val)) {
                            inputRepeatErrors.add(value);
                        }
                        //长度判断
                        if (val == null || val.isEmpty() || val.length() > 60 || val.length() == 0) {
                            longErrors.add(value);
                        }
                        entryValueList.add(val);
                    } else if (vals.length == 2) {
                        String val = vals[0];
                        //输入重复
                        if (StringUtils.hasText(val) && entryValueList.contains(val)) {
                            inputRepeatErrors.add(value);
                        }
                        //长度判断
                        if (val == null || val.isEmpty() || val.length() > 60 || val.length() == 0) {
                            longErrors.add(value);
                        }
                        //排序编号
                        String sortNumber = vals[1];
                        //判断是否是数字
                        if (!isNumOrEmpty(sortNumber)) {
                            notNumberErrors.add(value);
                        }
                        entryValueList.add(val);

                    } else {
                        //不符合规则
                        matchErrors.add(value);
                    }
                }
            }
        }
        //输入符合规则
        if (longErrors.isEmpty() && inputRepeatErrors.isEmpty() && notNumberErrors.isEmpty() && matchErrors.isEmpty()) {
            //判断系统是否重复
            for (String ev : entryValueList) {
                ListEntry entry = new ListEntry();
                entry.setEntryValue(ev);
                entry.setListId(listId);
            }
        }
        //返回结果
        if (longErrors.isEmpty() && inputRepeatErrors.isEmpty() && notNumberErrors.isEmpty() && matchErrors.isEmpty() && inputExistErrors.isEmpty()) {
            retMap.put("ret", true);
            retMap.put("detail", "success");
        } else {
            //校验不通过
            retMap.put("ret", false);
            StringBuilder reason = new StringBuilder();
            if (!longErrors.isEmpty()) {
                reason.append(String.format(" 列表值 %s 中列表值超过最大长度60", Arrays.toString(longErrors.toArray())));
            }
            if (!inputRepeatErrors.isEmpty()) {
                reason.append(String.format(" 列表值 %s 输入重复", Arrays.toString(inputRepeatErrors.toArray())));
            }
            if (!notNumberErrors.isEmpty()) {
                reason.append(String.format(" 列表值 %s 排序编号不为数字", Arrays.toString(notNumberErrors.toArray())));
            }
            if (!matchErrors.isEmpty()) {
                reason.append(String.format(" 列表值 %s 不符合填写规则", Arrays.toString(matchErrors.toArray())));
            }
            if (!inputExistErrors.isEmpty()) {
                reason.append(String.format(" 列表值 %s 系统中已存在", Arrays.toString(inputExistErrors.toArray())));
            }
            retMap.put("detail", reason.toString());
        }
        return retMap;
    }
}
